#-------------------------------------------------------------------------------
# Name:        Minigame
# Purpose:
#
# Author:      Pablo
#
# Created:     27/04/2013
# Copyright:   (c) Monxcleyr Productions 2013
# Licence:     GPL v3
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import pygame, os, random
from ..gui import label

class MiniGame():

  """class comment"""

  def __init__(self, common, debug):
    self.common = common
    self.menuSurface = pygame.Surface(self.common.initsize)
    self.debug = debug
    self.bg5 = pygame.image.load('resources/graphics/minigame/minigame.bmp')
    self.bg5.set_colorkey((255,0,255))
    self.bg6 = pygame.image.load('resources/graphics/minigame/minigame6.bmp')
    self.bg6.set_colorkey((255,0,255))
    self.cursor = pygame.image.load('resources/graphics/common/cursor.bmp')
    self.cursor.set_colorkey((255,0,255))
    self.sprites = [pygame.image.load('resources/graphics/minigame/0.bmp'),\
      pygame.image.load('resources/graphics/minigame/1.bmp'), \
      pygame.image.load('resources/graphics/minigame/2.bmp'), \
      pygame.image.load('resources/graphics/minigame/3.bmp'), \
      pygame.image.load('resources/graphics/minigame/4.bmp'), \
      pygame.image.load('resources/graphics/minigame/5.bmp'), \
      pygame.image.load('resources/graphics/minigame/6.bmp'), \
      pygame.image.load('resources/graphics/minigame/7.bmp')]
    self.buttonsprites = [pygame.image.load('resources/graphics/minigame/button_2.bmp'),\
      pygame.image.load('resources/graphics/minigame/button_3.bmp'), \
      pygame.image.load('resources/graphics/minigame/button_4.bmp'), \
      pygame.image.load('resources/graphics/minigame/button_5.bmp'), \
      pygame.image.load('resources/graphics/minigame/button_6.bmp'), \
      pygame.image.load('resources/graphics/minigame/button_7.bmp')]
    self.resetimage = pygame.image.load('resources/graphics/minigame/reset.bmp')
    self.font = pygame.font.Font('resources/fonts/system.ttf', 12)

    self.resetimage.set_colorkey((255,0,255))

    self.completed_easy = []
    self.completed_hard = []
    self.easy = []
    self.hard = []
    self.puzzle = ''
    self.findPuzzles('easy')
    self.findPuzzles('hard')
    self.selected = 0
    self.passed = None
    self.timelimit = None

  def findPuzzles(self, directory):
    count = 0

    for r,d,f in os.walk('resources/graphics/minigame/puzzles/' + directory):
      for files in f:
        if not files.endswith("solution.bmp"):
          count += 1
          if directory == 'easy':
            getattr(self, directory).append(files)
          else:
            getattr(self, directory).append(files)
          if directory == 'hard':
            getattr(self, directory).append(files)
          else:
            getattr(self, directory).append(files)



  def load(self, difficulty, timelimit=None):

    self.timelimit = timelimit

    searching = True
    while searching:

      rand = random.randint(0, len(getattr(self, difficulty)) - 1)
      searching = False
      self.puzzle = getattr(self, difficulty)[rand]
##      if getattr(self, difficulty)[rand] not in getattr(self, 'completed_' + difficulty):
##        searching = False
##        self.puzzle = getattr(self, difficulty)[rand]
##        getattr(self, difficulty).pop(rand)
##        getattr(self, 'completed_' + difficulty).append(self.puzzle)

    self.puzzleimage = pygame.image.load('resources/graphics/minigame/puzzles/' + difficulty + '/'+ self.puzzle)
    self.colorlist = []
    self.colors = []

    for row in range(0,self.puzzleimage.get_height()):
      for column in range(0,self.puzzleimage.get_width()):
        temp = self.puzzleimage.get_at((column, row))
        if temp == (0,0,0):
          temp = 1
        elif temp == (255,255,255):
          temp = 0
        elif temp == (255,0,0):
          temp = 2
        elif temp == (255,255,0):
          temp = 3
        elif temp == (0,255,255):
          temp = 4
        elif temp == (0,0,255):
          temp = 5
        elif temp == (255,0,255):
          temp= 6
        elif temp == (0,255,0):
          temp = 7

        temp = ((column, row), temp)
        self.colorlist.append(temp)


    for i in self.colorlist:
      if i[1] not in self.colors:
        self.colors.append(i[1])

    self.solutionimage = pygame.image.load('resources/graphics/minigame/puzzles/' + difficulty + '/' + self.puzzle[:-4] + '_solution.bmp')

    self.solution_colorlist = []
    for row in range(0,self.solutionimage.get_height()):
      for column in range(0,self.solutionimage.get_width()):
        temp = self.solutionimage.get_at((column, row))
        if temp == (0,0,0):
          temp = 1
        elif temp == (255,255,255):
          temp = 0
        elif temp == (255,0,0):
          temp = 2
        elif temp == (255,255,0):
          temp = 3
        elif temp == (0,255,255):
          temp = 4
        elif temp == (0,0,255):
          temp = 5
        elif temp == (255,0,255):
          temp= 6
        elif temp == (0,255,0):
          temp = 7
        temp = ((column, row), temp)
        self.solution_colorlist.append(temp)

##    print self.colorlist, self.solution_colorlist


    self.cells = []
    if self.puzzleimage.get_width() == 5:
      positions = []
      for j in range(0,5):
        for i in range(0,5):
          positions.append((388 + (i*50), 185 + (j *50)))
      for i in range(0, 25):
        if self.colorlist[i][1] != 0:
          self.cells.append(Cell(positions[i],self.colorlist[i][1], True, self.sprites, self.sprites[self.colorlist[i][1]]))
        else:
          self.cells.append(Cell(positions[i],self.colorlist[i][1], False, self.sprites))


      self.buttons = []
      for i in range(0,6):
        self.buttons.append(Button((390 + (i * 50), 138), i + 2, self.buttonsprites[i]))

      self.label = label.Label(self.menuSurface, ' ', (513, 115), 'center', self.font, (50, 132, 244))
      self.resetbutton = ResetButton((490,166), self.resetimage)



    if self.puzzleimage.get_width() == 6:
      positions = []
      for j in range(0,6):
        for i in range(0,6):
          positions.append((362 + (i*50), 172 + (j *50)))
      for i in range(0, 36):
        if self.colorlist[i][1] != 0:
          self.cells.append(Cell(positions[i],self.colorlist[i][1], True, self.sprites, self.sprites[self.colorlist[i][1]]))
        else:
          self.cells.append(Cell(positions[i],self.colorlist[i][1], False, self.sprites))


      self.buttons = []
      for i in range(0,6):
        self.buttons.append(Button((365 + (i * 50), 122), i + 2, self.buttonsprites[i]))

      self.label = label.Label(self.menuSurface, ' ', (513, 95), 'center', self.font, (50, 132, 244))
      self.resetbutton = ResetButton((490,151), self.resetimage)



    self.solution = []
    for cell in self.solution_colorlist:
      self.solution.append(cell[1])

    self.passed = None
    self.runningtime = 0



  def draw(self, gameS, starfield, mouse):

    if self.timelimit:
      displayedtime = self.timelimit - int(self.runningtime)
      self.label.setText(str(displayedtime))

      if displayedtime == 0:
        self.passed = False

    self.menuSurface.fill((0,0,0))

    # Draw the bg of the main screen here, so it looks liek the game is puased
##    self.menuSurface.blit(gameS, (0,0))
    starfield.draw(self.menuSurface)

    # MINIGAME CODE GOES HERE
    if self.puzzleimage.get_width() == 5:
      self.menuSurface.blit(self.bg5, (0,0))
    else:
      self.menuSurface.blit(self.bg6, (0,0))




    for cell in self.cells:
      cell.draw(self.menuSurface, mouse, self.selected)

    for button in self.buttons:
      if button.color in self.colors:
        temp = button.draw(self.menuSurface, mouse)
        if temp != None:
          self.selected = temp
          self.cursor = pygame.image.load('resources/graphics/common/cursor_' + str(temp) + '.bmp')
          self.cursor.set_colorkey((255,0,255))

    if self.resetbutton.draw(self.menuSurface, mouse):
      for cell in self.cells:
        cell.reset()


    if self.checkWin():
      self.passed = True

    self.label.draw()
    self.menuSurface.blit(self.cursor, mouse[0])
    # Return teh surface to be drawn, and whatever else would be needed
    return self.menuSurface

  def checkWin(self):

    celllist = []
    for cell in self.cells:
      celllist.append(cell.color)

    if celllist == self.solution:
      return True
    else:
      return False


class Cell():

  def __init__(self, position, color, static, spritelist, sprite=None):

    self.position = position
    self.color = color
    self.originalcolor = color
    self.static = static
    self.sprite = sprite
    self.spritelist = spritelist
    self.currentsprite = self.spritelist[self.color]

  def draw(self, surface, mouse, selected):

    rect =  self.currentsprite.get_rect()
    rect.topleft = self.position
    if rect.collidepoint(mouse[0]) and mouse[1] == 2:
      if not self.static:
        self.color = selected
        self.currentsprite = self.spritelist[self.color]

    if self.sprite:
      surface.blit(self.sprite, self.position)

    if not self.sprite and not self.static:
      surface.blit(self.currentsprite, self.position)

  def reset(self):
    self.color = self.originalcolor
    self.currentsprite = self.spritelist[self.color]



class Button():

  def __init__(self, position, color, sprite):

    self.position = position
    self.color = color
    # typing sprite so much makes me thirsty
    self.sprite = sprite

  def draw(self, surface, mouse):

    rect =  self.sprite.get_rect()
    rect.topleft = self.position
    selected = None
    if rect.collidepoint(mouse[0]) and mouse[1] == 1:
      selected = self.color
    surface.blit(self.sprite, self.position)
    return selected

class ResetButton():

  def __init__(self, position, sprite):
    self.position = position
    self.sprite = sprite
    rect = self.sprite.get_rect()
    rect.topleft = self.position
    self.rect = rect

  def draw(self, surface, mouse):

    surface.blit(self.sprite, self.position)

    if self.rect.collidepoint(mouse[0]) and mouse[1] == 1:
      return True
    else:
      return False